package com.xsprite.managesys.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xsprite.managesys.bean.XlsxFileBean;
import com.xsprite.managesys.log.LogManager;
import com.xsprite.managesys.service.ImportToDatabaseWorker;
import com.xsprite.managesys.service.ServerConfig;
import com.xsprite.managesys.service.ServersManager;
import com.xsprite.managesys.service.XlsxFileManager;


/**
 * Servlet implementation class TransferDBServlet
 */
public class TransferDBServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.service(req, resp);
		PrintWriter pw = resp.getWriter();
		try {
			String params = queryParam("paras");
			com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(params);
			JSONArray filesIds = jsonObj.getJSONArray("transferFiles");
			JSONArray serverNames = jsonObj.getJSONArray("updateServers");
			String userid = req.getSession().getAttribute("userid").toString();
			List<String> ids = extractFileIds(filesIds);
			List<XlsxFileBean> beans = XlsxFileManager.getInstance().getBeansByIds(ids);
			List<ServerConfig> serverConfigs = getServerConfigs(serverNames);
			if(beans.size()<=0 || serverConfigs.size() <= 0){
				LogManager.getInstance().log4j("userid " + userid + " 没有需要导入的文件或服务器");
				pw.print("没有需要导入的文件或服务器");
				return;
			}
			
			ImportToDatabaseWorker worker = new ImportToDatabaseWorker(serverConfigs, beans, userid);
			worker.work();
			pw.print(worker.getResult());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private List<String> extractFileIds(JSONArray filesArray){
		List<String> ids = new ArrayList<String>();
		for(int i = 0; i < filesArray.size(); i++){
			JSONObject obj = (JSONObject) filesArray.get(i);
			String fileId = obj.getString("tag");
			ids.add(fileId);
		}
		return ids;
	}
	
	private List<ServerConfig> getServerConfigs(JSONArray serverNames){
		List<ServerConfig> result = new ArrayList<ServerConfig>();
		for(int i = 0; i < serverNames.size(); i++){
			JSONObject obj = (JSONObject) serverNames.get(i);
			String serverName = obj.getString("tag");
			ServerConfig serverConfig = ServersManager.getInstance().getServerConfigByName(serverName);
			if (serverConfig == null) {
				throw new RuntimeException();
			} else {
				result.add(serverConfig);
			}
		}
		return result;
	}

	public String getRequestPayload(HttpServletRequest req) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = req.getReader();
		char[] buff = new char[1024];
		int len;
		while ((len = reader.read(buff)) != -1) {
			sb.append(buff, 0, len);
		}
		return sb.toString();
	}
}
